﻿using Devonline.Communication.Abstractions;
using Devonline.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Devonline.Communication.Server;

/// <summary>
/// 通讯服务器扩展方法
/// </summary>
public static class ServerExtensions
{
    /// <summary>
    /// 根据配置, 添加通讯服务器
    /// </summary>
    /// <param name="services"></param>
    /// <param name="setting"></param>
    /// <returns></returns>
    public static IServiceCollection AddCommunicationServer(this IServiceCollection services, HostSetting? setting = default)
    {
        setting ??= new HostSetting();
        if (setting.EnableCache && (!string.IsNullOrWhiteSpace(setting.CacheConfiguration)))
        {
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = setting.CacheConfiguration;
                options.InstanceName = setting.CachePrefix;
            });
        }
        else
        {
            services.AddDistributedMemoryCache();
        }

        if (setting.EnableIdentity && (!string.IsNullOrWhiteSpace(setting.IdentityDbContext)))
        {
            services.AddDbContext<IdentityDbContext>(options => options.UseNpgsql(setting.IdentityDbContext));
        }

        var signalRServerBuilder = services.AddSignalR();
        _ = setting.TransportType switch
        {
            TransportType.Json => signalRServerBuilder.AddJsonProtocol(config => config.PayloadSerializerOptions = AppSettings.JsonSerializerOptions),
            TransportType.MessagePack => signalRServerBuilder.AddMessagePackProtocol(config => config.SerializerOptions = MessagePack.MessagePackSerializerOptions.Standard),
            _ => signalRServerBuilder.AddNewtonsoftJsonProtocol(config => config.PayloadSerializerSettings = AppSettings.JsonSerializerSettings)
        };

        return services;
    }
}